package com.zhang.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhang.dao.ProductMapper;
import com.zhang.entity.Product;
import com.zhang.service.ProductService;
import com.zhang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class ProductServiceImpl implements ProductService {
    @Override
    public List<Product> selectCon(String orderby, int rownum) {
        List<Product> list = new ArrayList<>();
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            ProductMapper dao = sqlSession.getMapper(ProductMapper.class);
            list = dao.selectCon(orderby, rownum);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return list;
    }

    @Override
    public Product selectById(int id) {
        Product p = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            ProductMapper dao = sqlSession.getMapper(ProductMapper.class);
            p = dao.selectById(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return p;
    }

    @Override
    public PageInfo<Product> selectBooksByPage(int fcid,int scid, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        SqlSession sqlSession = null;
        PageInfo<Product> pi = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            ProductMapper dao = sqlSession.getMapper(ProductMapper.class);
            List<Product> list = dao.selectBooksByPage(fcid,scid);
            sqlSession.commit();
            pi = new PageInfo<>(list);
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return pi;
    }

}
